package controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import jdk.internal.org.objectweb.asm.commons.TryCatchBlockSorter;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import model.Userinfo;

import java.util.List;

public class IndexController extends Controller {
    public void index(){
        renderHtml("Hello world !");
    }
    public void hello(){
        String user = getPara("user");
        int age = getParaToInt("age");
        renderHtml("<h1>你好,"+user+"   你今年"+age+"岁</h1>");
    }

    public void main(){
        String user = getSessionAttr("user");
        String password = getSessionAttr("password");
        renderHtml("主页");

    }

    public void manager(){
        renderHtml("管理页面");
    }

    public void login(){
        renderFreeMarker("login.ftl");
    }

    public void doLogin(){
        String user = getPara("user");
        String password = getPara("password");

        List<Userinfo> userinfos = Userinfo.dao.find("SELECT * FROM t_userinfo WHERE user = ? AND password = ?", user, password);

        if(userinfos.size() != 0){
            redirect("/main");
            setSessionAttr("User",userinfos.get(0));
        }else {
            setAttr("errmsg","用户名或密码错误");
            renderFreeMarker("login.ftl");
        }
    }

    public void logout(){
        removeSessionAttr("User");
        redirect("/login");
    }

    public void register(){
        renderFreeMarker("register.ftl");
    }
    public void doRegister(){
        String user = getPara("user");
        String password = getPara("password");
        Integer sex = getParaToInt("sex");
        String hometown = getPara("hometown");

        Userinfo us = new Userinfo();
        us.setUser(user);
        us.setPassword(password);
        us.setSex(sex);
        us.setHometown(hometown);

        try {
            us.save();
        }catch (Exception e){
            LogKit.error("用户注册失败"+e.getMessage());
        }

        renderFreeMarker("login.ftl");
    }
}
